package mblog.web.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import mtons.modules.lang.Const;
import mtons.modules.pojos.UserContextHolder;
import mtons.modules.pojos.UserProfile;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.faxsun.web.utils.HttpContextHelper;

/**
 * 
 * 基础拦截器 - 向 request 中添加一些基础变量
 * 
 * @author langhsu
 * 
 *         对所有的response添加Header Access-Control-Allow-Origin:
 *         https://www.faxsun.com
 *         ，以便http页面发送https请求。对于浏览器，认为：https和http属于不同的domain
 * @author songdragon 2015-05-10 17:00
 * 
 */
public class BaseInterceptor extends HandlerInterceptorAdapter {

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		HttpSession session = request.getSession();
		UserProfile bean = (UserProfile) session.getAttribute(Const.KEY_LOGIN);
		UserContextHolder.setUserProfile(bean);
		HttpContextHelper.setSession(session);
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		if (request.getServletPath().equals("/logout")) {
			return;
		}
		HttpSession session = request.getSession();
		request.setAttribute("base", request.getContextPath());
		request.setAttribute("profile", session.getAttribute(Const.KEY_LOGIN));

		// https端口可配置
		String serverName = request.getServerName();
		response.setHeader("Access-Control-Allow-Origin", "http://"
				+ serverName + ":" + request.getServerPort());
		// response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Credentials", "true");
	}

}
